﻿using Core.Comamad;
using Core.ReadAndWrite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public class QLiTaiKhoan : IQuanLi
    {
        public List<BaseData> data = new List<BaseData>();
        #region Singleton
        private static QLiTaiKhoan _Instance;
        private static object locks = new object();

        public static QLiTaiKhoan Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (locks)
                    {
                        if (_Instance == null)
                            _Instance = new QLiTaiKhoan();
                    }
                }
                return _Instance;
            }
        }
        #endregion

        #region Command
        List<ICommand> _commands = new List<ICommand>();
        private int Current
        {
            get
            {
                return _commands.Count;

            }
            set
            {
                Current = value;
            }
        }
        public void Undo()
        {
            if (Current > 0)
            {
                var count = (int)Current - 1;
                ICommand cms = _commands[count];
                cms.UnExecute();
            }
        }
        #endregion
        public QLiTaiKhoan()
        {
            data = DataSource.Instance.ReadTaiKhoan("DsTaiKhoan.txt");
        }
        public void Add(BaseData ob)
        {
            data.Add(ob);
        }

        public void Delete(BaseData ob)
        {
            data.Remove(ob);
        }

        public void Update(BaseData ob)
        {
            TaiKhoan tk = ob as TaiKhoan;
            TaiKhoan find = data.Find(c => (c as TaiKhoan).Username == tk.Username) as TaiKhoan;
            TaiKhoan t = new TaiKhoan
            {
                ID = find.ID,
                Username = find.Username,
                Password = find.Password,
                PhanQuyen = find.PhanQuyen
            };
            find.ID = tk.ID;
            find.Username = tk.Username;
            find.Password = tk.Password;
            find.PhanQuyen = tk.PhanQuyen;
            ICommand tem = new ObCommand(LoaiXuLi.Update, t);
            _commands.Add(tem);

        }

        public List<BaseData> FindAll(Predicate<BaseData> Predicate)
        {
            return data.FindAll(Predicate);
        }

        public BaseData Find(Func<BaseData, bool> predicate)
        {
            return data.FirstOrDefault(predicate);
        }
    }
}
